package cn.wolfcode.mq;

import cn.wolfcode.ws.OrderWSListener;
import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.checkerframework.checker.units.qual.C;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

// 结果消息消费者监听，消费模式为广播模式，这里的模式为了解决如果websocket集群的情况下找不到拥有token的会
// 话可能要不到消息消费
@Component
@RocketMQMessageListener(consumerGroup = "orderWSGroup",topic = MQConstants.ORDER_RESULT_TOPIC,messageModel = MessageModel.BROADCASTING)
public class OrderResultListener implements RocketMQListener<OrderMQResult> {
    @Override
    public void onMessage(OrderMQResult orderMQResult) {
        System.out.println("消失内容" + JSON.toJSONString(orderMQResult));
        String token = orderMQResult.getToken();
        int count = 0;
        do {
            Session session = OrderWSListener.clients.get(token);
            if (session != null) {
                try {
                    session.getBasicRemote().sendText(JSON.toJSONString(orderMQResult));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return;
            }
            count ++;
            try {
                // 等待一下，以免token会话关系还没建立好长链接，消息结果就到了
                TimeUnit.MILLISECONDS.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } while (count < 3);
    }
}
